package common.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class UploadUtil {

    private final static String ACCESSKEY = "in1PI6uSce9R9-ZoiJZ_AjH3DRUdPwgpDh7YlDfC";
    private final static String SECRETKEY = "fVy6qph1sENVMyW8z6A1dumUgd3hfitok-JyT3Ef";
    private final static String BUCKET = "heima113";
    private final static String URL = "http://q1at03g2e.bkt.clouddn.com/";

    public static void main(String[] args) throws Exception {
        File file = new File("F:\\资料\\200多套合集扁平化动态 静态 ppt模板 图表素材\\静态模板\\1-10\\幻灯片3.JPG");
        InputStream input = new FileInputStream(file);
        byte[] byt = new byte[input.available()];
        input.read(byt);
        //http://q1at03g2e.bkt.clouddn.com/FlfH5iAvjlZynhVmgKhpqerzyQDd
        System.out.println(new UploadUtil().upload(byt));

    }

    public static String upload(byte[] uploadBytes){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        /*String accessKey = "your access key";
        String secretKey = "your secret key";
        String bucket = "your bucket name";*/
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            //byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
            String upToken = auth.uploadToken(BUCKET);
            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                key = putRet.key;
//                System.out.println(putRet.key);
//                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return URL+key;
    }
}
